package zju.dgm.zkhandle;


import lombok.Data;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * @author lzy
 */
@Configuration
@PropertySource("classpath:application.properties")
@ConfigurationProperties(prefix = "zk.server")
@Data
public class ZkClientConfig {


    private String[] addrs;

    private int sessionTimeoutMs;

    private int connectionTimeoutMs;


    @Bean
    public CuratorFramework getClient() {
        CuratorFramework client = CuratorFrameworkFactory.newClient(
                // 从各个zk服务器port中随机选取一个进入
                addrs[(int) (Math.random() * addrs.length)],
                sessionTimeoutMs, connectionTimeoutMs,
                new ExponentialBackoffRetry(1000, 3));
        client.start();
        try {
            // 请求一次保证联通
            client.getChildren().forPath("/");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }


}
